from flask import Blueprint, request, redirect, url_for
from common.libs.Helper import ops_renderJSON, iPagenation, ops_render
from common.models.collect_index import CollectIndex
from common.models.collect_detail import CollectDetail
from common.models.collect_all import CollectAll
from common.models.user import User
from application import db, app
from common.libs.DataHelper import getCurrentTime
import flask_excel as excel
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager
import os

collect_page = Blueprint("collect_page", __name__)


def pagesadmin(index):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': index.count(),
        "page_size": 8,
        'page': page,
        'url': "/collect/collectindex?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    index = index[offset:limit]

    return pages, index


def pagessearch(index, url):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': index.count(),
        "page_size": 8,
        'page': page,
        'url': "/collect/collectindex?" + url,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    index = index[offset:limit]

    return pages, index


@collect_page.route('/collectall', methods=['GET', 'POST'])
def collectall():
    classone = ["绩效类", "薪酬类"]
    para = [{"class": "tab-pane active", "id": "one", "num": 0}, {"class": "tab-pane", "id": "two", "num": 1}]
    num = []
    for item in classone:
        datanum = CollectAll.query.filter_by(part=item, mark=1).count()
        num.append(datanum)

    alldetail = []
    for item in classone:
        detail = CollectAll.query.filter_by(part=item, mark=1).all()
        alldetail.append(detail)

    return ops_render("/collect/collectall.html", {"num": num, "alldetail": alldetail, "para": para})


@collect_page.route('/collectindex', methods=['GET', 'POST'])
def collectindex():
    id = request.args.get("id")
    collectall = CollectAll.query.filter_by(mark=1,id=id).first()
    collectindex = CollectIndex.query.filter_by(mark=1,aid=id).order_by(CollectIndex.created_time.desc())
    pages, collectindex = pagesadmin(collectindex)
    return ops_render("/collect/collectindex.html", {"collectindex": collectindex, "pages": pages,"collectall":collectall })


@collect_page.route('/collectsearch', methods=['GET', 'POST'])
def collectsearch():
    a = request.args.to_dict()
    for key in list(a.keys()):
        if a.get(key) == "不限":
            del a[key]
    for key in list(a.keys()):
        if not a.get(key):
            del a[key]
    if "p" in a:
        del a["p"]

    type = request.args.get('type')
    sn = request.args.get('sn')
    form = request.args.get('form')
    projectname = request.args.get('projectname')
    company = request.args.get('company')
    isover = request.args.get('isover')
    url = "type=" + type + "&sn=" + sn + "&form=" + form + "&projectname=" + projectname + "&company=" + company + "&isover=" + isover + "&mark=1"

    bookindex = CollectIndex.query.filter_by(**a).order_by(CollectIndex.created_time.desc())
    pages, bookindex = pagessearch(bookindex, url)

    return ops_render("/collect/collectindex.html", {"collectindex": collectindex, "pages": pages})


# 搜索函数
def make_excel_list(data, column_names):
    list_data = []
    list_data.append(column_names)
    for item in data:
        tmp = [item.htsn, item.name, item.project, item.aname, item.bname, item.filename, item.filenum, item.num,
               item.dfnum, item.cwnum, item.cdnum, item.creater.nickname, item.creater.company, item.creater.department]
        list_data.append(tmp)
    return list_data


# 新增分类
@collect_page.route('/addall', methods=['GET', 'POST'])
def addall():
    req = request.values
    part = req['part'] if "part" in req else ""
    name = req['name'] if "name" in req else ""
    uid = req['uid'] if "uid" in req else ""

    index = CollectAll()
    index.name = name
    index.mark = 1
    index.uid = uid
    index.part = part
    index.created_time = index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()

    return ops_renderJSON(msg="新建成功")


# 修改分类信息
@collect_page.route('/updataall', methods=['GET', 'POST'])
def updataall():
    req = request.values
    id = req['id'] if "id" in req else ""
    part = req['part'] if "part" in req else ""
    name = req['name'] if "name" in req else ""
    uid = req['uid'] if "uid" in req else ""

    index = CollectAll.query.filter_by(id=id).first()
    index.part = part
    index.name = name
    index.uid = uid
    index.updated_time = getCurrentTime()
    db.session.commit()
    return ops_renderJSON(msg="更新成功")

# 删除分类信息
@collect_page.route('/deleteall', methods=['GET', 'POST'])
def deleteall():
    id = request.args.get("id")
    index = CollectAll.query.filter_by(id=id).first()
    index.mark = 0
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return redirect(url_for('collect_page.collectall', id=id))


# 新增二级分类
@collect_page.route('/addindex', methods=['GET', 'POST'])
def addindex():
    req = request.values
    aid = req['aid'] if "aid" in req else ""
    name = req['name'] if "name" in req else ""
    uid = req['uid'] if "uid" in req else ""
    bz = req['bz'] if "bz" in req else ""


    index = CollectIndex()
    index.name = name
    index.mark = 1
    index.uid = uid
    index.aid = aid
    index.bz = bz
    index.created_time = index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()

    return ops_renderJSON(msg="新建成功")


# 修改二级分类
@collect_page.route('/updataindex', methods=['GET', 'POST'])
def updataindex():
    req = request.values
    id = req['id'] if "id" in req else ""
    name = req['name'] if "name" in req else ""
    uid = req['uid'] if "uid" in req else ""
    bz = req['bz'] if "bz" in req else ""

    index = CollectIndex.query.filter_by(id=id).first()
    index.name = name
    index.uid = uid
    index.bz = bz
    index.updated_time = getCurrentTime()
    db.session.commit()
    return ops_renderJSON(msg="更新成功")

# 删除二级分类
@collect_page.route('/deleteindex', methods=['GET', 'POST'])
def deleteindex():
    id = request.args.get("id")
    index = CollectIndex.query.filter_by(id=id).first()
    index.mark = 0
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return redirect(url_for('collect_page.collectall', id=id))


# 详情页展示
@collect_page.route('/collectdetail', methods=['GET', 'POST'])
def collectdetail():
    id = request.args.get("id")
    collectdetail = CollectDetail.query.filter_by(pid=id, mark=1).all()
    collectindex = CollectIndex.query.filter_by(id=id).first()
    collectall = CollectAll.query.filter_by(id=collectindex.aid).first()
    return ops_render("/collect/collectdetail.html",
                      {"collectindex": collectindex, "collectdetail": collectdetail,"collectall": collectall})


# 上传文件
@collect_page.route('/upload', methods=['GET', 'POST'])
def uploadfile():
    # 从前端获取文件
    f = request.files.get('files')
    pid = request.form.get('pid')
    classone = request.form.get('classone')
    classtwo = request.form.get('classtwo')
    uid = request.form.get('uid')
    userinfo = User.query.filter_by(id=uid).first()
    company=userinfo.company
    city=userinfo.city
    nickname=userinfo.nickname

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'

    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'collect-filestore'
    # http://+外链域名
    domian_name = 'http://collectfilestore.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等

    file = f.read()
    name = f.filename
    name, type1 = os.path.splitext(name)
    type = type1.replace(".", "")
    size = len(file) / 1000000
    size = round(size, 2)

    uploadname = classone+"-"+classtwo+"("+company+"-"+city+"-"+nickname+")"+"."+type
    detailname = CollectDetail.query.filter_by(name=uploadname,mark=1).first()
    if detailname :
        return ops_renderJSON(msg="文件冲突，请删除先前的文件后再上传")
    else:
        token = q.upload_token(bucket_name, uploadname, 3600)
        ret, info = put_data(token, uploadname, data=file)
        url = domian_name + uploadname

        detail = CollectDetail()
        detail.name = uploadname
        detail.type = type
        detail.size = size
        detail.url = url
        detail.mark = 1
        detail.uid = uid
        detail.pid = pid
        detail.created_time = detail.updated_time = getCurrentTime()
        db.session.add(detail)
        db.session.commit()

        return ops_renderJSON(msg="上传成功")



@collect_page.route('/detaildelete', methods=['GET', 'POST'])
def deletedetail():
    id = request.args.get('id')
    detail = CollectDetail.query.filter_by(id=id).first()

    uploadname = detail.name
    pid=detail.pid

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 初始化Auth状态
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    bucket_name = 'collect-filestore'
    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, uploadname)
    if info.status_code == 200:
        collectdetail1 = CollectDetail.query.filter_by(id=id).first()
        collectdetail1.mark = 0
        db.session.commit()
        return redirect(url_for('collect_page.collectdetail', id=pid))
    else:
        return ops_renderJSON(msg="删除失败")


@collect_page.route('/delete', methods=['GET', 'POST'])
def detail():
    id = request.args.get('id')
    type=request.args.get('type')
    if type == "all":
        collectall = CollectAll.query.filter_by(id=id).first()
        collectall.mark = 0
        db.session.commit()
        return redirect(url_for('collect_page.collectall'))

    if type == "index":
        aid = request.args.get('aid')
        collectindex = CollectIndex.query.filter_by(id=id).first()
        collectindex.mark = 0
        db.session.commit()
        return redirect(url_for('collect_page.collectindex', id=aid))


